<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>自定义查询添加编辑</title>
        <link rel="stylesheet" href="${ctx}/css/form.css">
        <#include "/pubHeadStyle.html">
    </head>
    <body style="overflow-y: auto;">
        <form class="layui-form" lay-filter="templateForm" style="margin:0 10px;padding-top:10px;">
            <div class="layui-form-item">
                <div>
                    <a lay-submit lay-filter="dataTemplateForm" class="layui-btn layui-btn-sm btn-n" id="save">保存</a>
                    <a class="layui-btn layui-btn-sm" id="preview">预览</a>
                    <a class="layui-btn layui-btn-sm" id="editTemplate">编辑模板</a>
                    <a class="layui-btn layui-btn-sm" id="addMenu">添加为菜单</a>
                    <a class="layui-btn layui-btn-danger layui-btn-sm btn-save" id="cancel">取消</a>
                </div>
            </div>
            <div class="layui-tab layui-tab-card">
                <ul class="layui-tab-title">
                    <li class="layui-this">基本信息</li>
                    <li>显示列字段</li>
                    <li>查询条件字段</li>
                    <li>排序字段</li>
                    <li>过滤条件</li>
                    <li>导出字段</li>
                    <li>功能按钮</li>
                </ul>
                <div class="layui-tab-content">
                    <div class="layui-tab-item layui-show">
                        <table class="table-detail">
                            <tr>
                                <th style="width:16%;">表单别名:</th>
                                <td style="width:100%"><input type="text" class="layui-input" name="formKey"
                                                              value="${formKey}"
                                                              maxlength="33" readonly>
                                </td>
                            </tr>
                            <tr class="passdis">
                                <th>绑定流程:</th>
                                <td><input type="text" name="subject" autocomplete="off" readonly id="subject"
                                           class="layui-input" maxlength="33" style="display:inline-block">
                                    <input type="hidden" id="defId" name="defId">

                                    <button style="margin:0 5px 0 15px" class="layui-btn layui-btn-sm" type="button"
                                            id="opt">选择
                                    </button>
                                    <button class="layui-btn layui-btn-sm" type="button" id="reset">重置</button>

                                </td>
                            </tr>
                            <tr>
                                <th>是否分页:</th>
                                <td style="padding-left:6px;position: relative" id="paging">
                                    <input type="radio" name="needPage" value="0" title="不分页" lay-filter="paging">
                                    <input type="radio" name="needPage" value="1" title="分页" checked
                                           lay-filter="paging">

                                    <span class="isPage">分页大小:</span>
                                    <span class="isPage" id="isPage">
                                        <select name="pageSize">
                                            <option value="5">5 条/页</option>
                                            <option value="10">10 条/页</option>
                                            <option value="15">15 条/页</option>
                                            <option value="20" selected>20 条/页</option>
                                            <option value="50">50 条/页</option>
                                        </select>
                                    </span>

                                </td>
                            </tr>
                            <tr>
                                <th>是否初始查询:</th>
                                <td>
                                    <select name="isQuery" id="isQuery" lay-filter="initQuery">
                                        <option value="0">是</option>
                                        <option value="1">否</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <th>没有过滤条件
                                    是否需要默认过滤:
                                </th>
                                <td>
                                    <select name="isFilter" id="isFilter" lay-filter="initTable">
                                        <option value="1">是</option>
                                        <option value="0">否</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <th>数据模板:<span style="color:red;">*</span></th>
                                <td>
                                    <select name="templateAlias" id="templateAlias" lay-verify="required">
                                        <option value=""></option>
                                    </select>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <!--显示列-->
                    <div class="layui-tab-item fieldTable">
                        <div style="height: 427px;overflow-y: auto;overflow-x: hidden;">
                            <table class="layui-hide" id="fieldTable" lay-filter="fieldTable"></table>
                        </div>
                    </div>
                    <!--查询条件-->
                    <div class="layui-tab-item">
                        <div id="queryField">
                            <iframe src="" frameborder="0" width="100%" height="400" scrolling="auto"
                                    id="conditionIframe"></iframe>
                        </div>
                    </div>
                    <!--排序-->
                    <div class="layui-tab-item">
                        <div id="root">
                            <iframe src="" frameborder="0" width="100%" height="500" scrolling="auto"
                                    id="sortIframe"></iframe>
                        </div>
                    </div>
                    <!--过滤条件-->
                    <div class="layui-tab-item">
                        <a class="layui-btn layui-btn-sm" id="addFilter" style="margin:10px;">添加</a>
                        <div id="filterCell">
                            <table class="layui-hide" id="condition" lay-filter="condition"></table>
                        </div>
                    </div>
                    <!--导出字段-->
                    <div class="layui-tab-item exportField" style="height: 552px;overflow-y: auto;overflow-x: hidden;">
                        <p style="margin:0 auto;text-align: center;padding:15px 0" id="tableInfo"></p>
                        <table id="exportField" lay-filter="exportField"></table>
                        <div class="childTable">
                        </div>
                    </div>
                    <!--功能按钮-->
                    <div class="layui-tab-item">
                        <div id="buttonBox">
                            <div class="table-top-left">
                                <div class="toolBar" style="margin:0;padding:15px 0 15px 5px">
                                    <div class="group">
                                        <a class="layui-btn layui-btn-sm" id="btnFunctionAdd">添加</a>
                                        <a class="layui-btn layui-btn-sm" id="btnFunctionInit">初始化</a>
                                    </div>
                                </div>
                            </div>
                            <table class="layui-hide" id="functionField" lay-filter="functionField"></table>
                        </div>
                    </div>
                </div>
            </div>
        </form>

        <script type="text/html" id="rowOperation">
            <a class="layui-btn layui-btn-xs" lay-event="moveup">上移</a>
            <a class="layui-btn layui-btn-xs" lay-event="movedown">下移</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
        </script>
        <script type="text/html" id="filterRowOperation">
            <a class="layui-btn layui-btn-xs" lay-event="moveup">上移</a>
            <a class="layui-btn layui-btn-xs" lay-event="movedown">下移</a>
            <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
        </script>
        <script type="text/html" id="power">
            <select class="layui-yonyou-select" lay-ignore name="istrue" lay-filter="istrue">
                <option value=""></option>
                <option value="false">否</option>
                <option value="true">是</option>
            </select>
        </script>
        <script type="text/html" id="factor">
            <select class="layui-yonyou-select" lay-ignore name="istrue" lay-filter="istrue">
                <option value="">请选择</option>
                <option value="1">=</option>
                <option value="2">!=</option>
                <option value="3">like</option>
            </select>
        </script>
        <script type="text/html" id="valueSource">
            <select class="layui-yonyou-select" lay-ignore name="istrue" lay-filter="istrue">
                <option value="">请选择</option>
                <option value="1">表单输入</option>
                <option value="2">动态传入</option>
            </select>
        </script>
        <script type="text/html" id="export">
            <div id="exportFiled">
                <select class="layui-yonyou-select" name="rightSelect" lay-filter="rightSelect">
                    <option value="">请选择</option>
                    <option value="none">无</option>
                    <option value="everyone">所有人</option>
                    <option value="user">用户</option>
                    <option value="role">角色</option>
                    <option value="org">组织</option>
                    <option value="orgMgr">组织负责人</option>
                    <option value="pos">岗位</option>
                    <option value="script">脚本</option>
                </select>
            </div>
        </script>
        <!--功能按钮页模板-开始-->
        <script type="text/html" id="functionTypeTemplate">
            <div id="functionType">
                <select class="layui-yonyou-select" lay-filter="functionType" name="{{d.id+'FunctionType'}}">
                    <option value="add">新增</option>
                    <option value="edit">编辑</option>
                    <option value="batchDel">批量删除</option>
                    <option value="del">删除</option>
                    <option value="detail">明细</option>
                    <option value="export">导出</option>
                    <option value="import">导入</option>
                    <option value="start">启动流程</option>
                    <option value="reStart">重启流程</option>
                </select>
            </div>
        </script>
        <script type="text/html" id="powerTypeTemplate">
            <div class="powerType">
                <select class="layui-yonyou-select" lay-filter="powerType" name="{{d.id+'PowerType'}}">
                    <option value="">请选择</option>
                    <option value="none">无</option>
                    <option value="everyone">所有人</option>
                    <option value="user">用户</option>
                    <option value="role">角色</option>
                    <option value="org">组织</option>
                    <option value="orgMgr">组织负责人</option>
                    <option value="pos">岗位</option>
                    <option value="script">脚本</option>
                </select>
            </div>
            {{#  if(d.right[0].type == 'user' || d.right[0].type == 'role'|| d.right[0].type == 'org'|| d.right[0].type == 'orgMgr'|| d.right[0].type == 'pos'){ }}
            <div style="position: absolute; top: 0px; left: 198px;">
                <input type="text" id="{{'namesPower'+d.id}}" class="layui-input" value="{{d.right[0].names}}"
                       style="float: left;height: 30px;margin-right:5px;width:180px;"/>
                <button type="button" onclick="selectButton(this)" class="layui-btn layui-btn-xs selectUser"
                        inputIndex="{{'Power'+d.id}}">选择
                </button>
                <input type="hidden" id="{{'idsPower'+d.id}}" value="{{d.right[0].ids}}"/>
            </div>
            {{#  }}}

            {{#  if(d.right[0].type == 'script'){ }}
            <div style="position: absolute; top: 0px; left: 198px;">
        <textarea class="layui-input" id="{{'namesPower'+d.id}}"
                  style="float: left;height: 30px;width: 200px;margin-right:5px;">{{d.right[0].script}}</textarea>
                <button type="button" onclick="selectScript(this)" class="layui-btn layui-btn-xs"
                        inputIndex="{{'Power'+d.id}}">
                    常用脚本
                </button>
                <textarea class="layui-input" id="{{'idsPower'+d.id}}"
                          style="display:none;">{{d.right[0].rightScript}}</textarea>
            </div>
            {{#  }}}
        </script>
        <!--功能按钮页模板-结束-->

        <!--过滤条件页模板-开始-->
        <script type="text/html" id="filterTypeTemplate">
            {{#  if(d.type == '1'){ }}
            条件脚本
            {{#  }}}
            {{#  if(d.type == '2'){ }}
            SQL
            {{#  }}}
        </script>
        <script type="text/html" id="filterPowerTypeTemplate">
            <div class="filterPowerType">
                <select class="layui-yonyou-select" lay-filter="filterPowerType" name="{{d.id+'FilterPowerType'}}">
                    <option value="">请选择</option>
                    <option value="none">无</option>
                    <option value="everyone">所有人</option>
                    <option value="user">用户</option>
                    <option value="role">角色</option>
                    <option value="org">组织</option>
                    <option value="orgMgr">组织负责人</option>
                    <option value="pos">岗位</option>
                    <option value="script">脚本</option>
                </select>
            </div>
            {{#  if(d.right[0].type == 'user' || d.right[0].type == 'role'|| d.right[0].type == 'org'|| d.right[0].type == 'orgMgr'|| d.right[0].type == 'pos'){ }}
            <div style="position: absolute; top: 0px; left: 198px;">
                <input type="text" id="{{'namesFilterPower'+d.id}}" class="layui-input" value="{{d.right[0].names}}"
                       style="float: left;height: 30px;margin-right:5px;"/>
                <button type="button" onclick="selectButton(this)" class="layui-btn layui-btn-xs selectUser"
                        inputIndex="{{'FilterPower'+d.id}}">选择
                </button>
                <input type="hidden" id="{{'idsFilterPower'+d.id}}" value="{{d.right[0].ids}}"/>
            </div>
            {{#  }}}

            {{#  if(d.right[0].type == 'script'){ }}
            <div style="position: absolute; top: 0px; left: 198px;">
        <textarea class="layui-input" id="{{'namesFilterPower'+d.id}}"
                  style="float: left;height: 30px;width: 200px;margin-right:5px;">{{d.right[0].script}}</textarea>
                <button type="button" onclick="selectScript(this)" class="layui-btn layui-btn-xs"
                        inputIndex="{{'FilterPower'+d.id}}">常用脚本
                </button>
                <textarea class="layui-input" id="{{'idsFilterPower'+d.id}}"
                          style="display:none;">{{d.right[0].rightScript}}</textarea>
            </div>
            {{#  }}}
        </script>
        <!--过滤条件页模板-结束-->
        <script src="${ctx}/extends/jquery.min.js" type="text/javascript"></script>
        <script>
            var setter = layui.setter;
            var sortField;
            //是否是外部表
            var isOutTable;
            var conditionField;
            var fieldArr;
            var formKey = '${formKey}';
            var dataTemplateCount = '${dataTemplateCount}';
            if (dataTemplateCount == 0) {
                $("#preview").hide();
                $("#editTemplate").hide();
                $("#addMenu").hide();
            }
            $("#addMenu").click(function () {
                parent.layer.open({
                    type: 2,
                    title: "添加资源",
                    shade: 0.3,
                    area: ['900px', '585px'],
                    content: serverPath.formPath + setter.formLinkPath + 'formDef/view/resMenu?formKey=' + formKey
                })
            });

            $("#preview").click(function () {
                window.open(serverPath.formPath + setter.formLinkPath + 'dataTemplate/view/preview?formKey=' + formKey);
            });

            //脚本选择器
            function selectScript(ele) {
                var ids = $(ele).next().attr("id");
                var names = $(ele).prev().attr("id");
                layer.open({
                    type: 2,
                    area: ['800px', '540px'],
                    title: ['脚本'],
                    content: serverPath.formPath + setter.formLinkPath + "table/view/templateScript?ids=" + ids + "&names=" + names
                });
            }


            //显示的列和 导出字段  用的脚本选择器
            function selectorScript(ele) {
                var ids = $(ele).prev().attr("id");
                var names = $(ele).prev().prev().attr("id");
                layer.open({
                    type: 2,
                    area: ['800px', '540px'],
                    title: ['脚本'],
                    content: serverPath.formPath + setter.formLinkPath + "table/view/templateScript?ids=" + ids + "&names=" + names
                });
            }

            //功能按钮 和 过滤条件 权限选择器
            function selectButton(ele) {
                var attrId = $(ele).attr("inputIndex");
                var selectValue = $(ele).parent().prev().children("select").val();
                if (undefined === selectValue) {
                    selectValue = $(ele).parent().prev().prev().val();
                }
                //人员选择器
                if (selectValue === 'user') {
                    var userSelectorWin;
                    var body;
                    var userNameArray = [], userIdArray = [];
                    layer.open({
                        type: 2,
                        title: "人员选择器",
                        shade: 0.3,
                        resize: false,
                        area: ['970px', '540px'],
                        btn: ["保存", "取消", "撤销"],
                        content: serverPath.formPath + setter.sysLinkPath + "dialog/view/sysUserDialog",
                        success: function (layero, index) {
                            body = layer.getChildFrame('body', index);
                            userSelectorWin = window[layero.find('iframe')[0]['name']];
                            userSelectorWin.layui.userList = [];
                            var names = $("#names" + attrId).val();
                            var ids = $("#ids" + attrId).val();
                            if (ids !== "" && names !== "") {
                                userNameArray = names.split(",");
                                userIdArray = ids.split(",");
                                for (var i = 0; i < userIdArray.length; i++) {
                                    userSelectorWin.layui.userList.push({
                                        name: userNameArray[i],
                                        userId: userIdArray[i]
                                    });
                                }
                            }
                        },
                        yes: function (index, layero) {
                            userNameArray = [], userIdArray = [];
                            var userList = body.find("input[name=userList]").val();
                            if (userList) {
                                layui.each(JSON.parse(userList), function (index, item) {
                                    userNameArray.push(item.name);
                                    userIdArray.push(item.userId);
                                });
                            }
                            $("#names" + attrId).val(userNameArray.join(","));
                            $("#ids" + attrId).val(userIdArray.join(","));
                            layer.close(index);
                        },
                        btn3: function (index, layero) {
                            userSelectorWin.cancelData(index);
                            return false //开启该代码可禁止点击该按钮关闭
                        }
                    });
                }
                //组织 或 组织负责人 选择器
                if (selectValue === 'org' || selectValue === 'orgMgr') {
                    var orgSelectorWin;
                    var body;
                    var orgNameArray = [], orgIdArray = [];
                    layer.open({
                        type: 2,
                        title: "组织选择器",
                        shade: 0.3,
                        resize: false,
                        area: ['970px', '540px'],
                        btn: ["保存", "取消", "撤销"],
                        content: serverPath.formPath + setter.sysLinkPath + "dialog/view/sysOrgDialog",
                        success: function (layero, index) {
                            body = layer.getChildFrame('body', index);
                            orgSelectorWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                            orgSelectorWin.layui.orgList = [];
                            var names = $("#names" + attrId).val();
                            var ids = $("#ids" + attrId).val();
                            if (ids !== "" && names !== "") {
                                orgNameArray = names.split(",");
                                orgIdArray = ids.split(",");
                                for (var i = 0; i < orgIdArray.length; i++) {
                                    orgSelectorWin.layui.orgList.push({name: orgNameArray[i], orgId: orgIdArray[i]});
                                }
                            }
                        },
                        yes: function (index, layero) {
                            orgNameArray = [], orgIdArray = [];
                            var orgList = body.find("input[name=orgList]").val();
                            if (orgList) {
                                layui.each(JSON.parse(orgList), function (index, item) {
                                    orgNameArray.push(item.name);
                                    orgIdArray.push(item.orgId);
                                });
                            }
                            $("#names" + attrId).val(orgNameArray.join(","));
                            $("#ids" + attrId).val(orgIdArray.join(","));
                            layer.close(index);
                        },
                        btn3: function (index, layero) {
                            orgSelectorWin.cancelData(index);
                            return false //开启该代码可禁止点击该按钮关闭
                        }
                    });
                }
                //组织 或 组织负责人 选择器
                if (selectValue === 'role') {
                    var roleSelectorWin;
                    var body;
                    var roleNameArray = [], roleIdArray = [];
                    layer.open({
                        type: 2,
                        title: "角色选择器",
                        shade: 0.3,
                        resize: false,
                        area: ['970px', '540px'],
                        btn: ["保存", "取消", "撤销"],
                        content: serverPath.formPath + setter.sysLinkPath + "dialog/view/sysRoleDialog",
                        success: function (layero, index) {
                            body = layer.getChildFrame('body', index);
                            roleSelectorWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                            roleSelectorWin.layui.roleList = [];
                            var names = $("#names" + attrId).val();
                            var ids = $("#ids" + attrId).val();
                            if (ids !== "" && names !== "") {
                                roleNameArray = names.split(",");
                                roleIdArray = ids.split(",");
                                for (var i = 0; i < roleIdArray.length; i++) {
                                    roleSelectorWin.layui.roleList.push({
                                        name: roleNameArray[i],
                                        roleId: roleIdArray[i]
                                    });
                                }
                            }
                        },
                        yes: function (index, layero) {
                            roleNameArray = [];
                            roleIdArray = [];
                            var roleList = body.find("input[name=roleList]").val();
                            if (roleList) {
                                layui.each(JSON.parse(roleList), function (index, item) {
                                    roleNameArray.push(item.name);
                                    roleIdArray.push(item.roleId);
                                });
                            }
                            $("#names" + attrId).val(roleNameArray.join(","));
                            $("#ids" + attrId).val(roleIdArray.join(","));
                            layer.close(index);
                        },
                        btn3: function (index, layero) {
                            roleSelectorWin.cancelData(index);
                            return false //开启该代码可禁止点击该按钮关闭
                        }
                    });
                }
            }

            //功能按钮页，表头权限select
            function selectPower(obj) {
                var typeValue = $(obj).find("option:selected").val();
                var divArray = $("div .powerType");
                if (divArray.length > 0) {
                    if (typeValue === 'everyone' || typeValue === 'none') {
                        for (var i = 0; i < divArray.length; i++) {
                            $(divArray[i]).children("select").val(typeValue);
                            $(divArray[i]).next('div').remove();
                        }
                        form.render('select');
                    }
                }
            }

            //过滤条件页，表头权限select
            function selectFilterPower(obj) {
                var typeValue = $(obj).find("option:selected").val();
                var divArray = $("div .filterPowerType");
                if (divArray.length > 0) {
                    if (typeValue === 'everyone' || typeValue === 'none') {
                        for (var i = 0; i < divArray.length; i++) {
                            $(divArray[i]).children("select").val(typeValue);
                            $(divArray[i]).next('div').remove();
                        }
                        form.render('select');
                    }
                }
            }

            var form;
            layui.config({
                base: serverPath.formPath + staticPath.formPath //静态资源所在路径
            }).extend({
                index: 'index' //主入口模块
            }).use(['index', 'element', 'form', 'layer', 'laydate', 'upload', 'setter', 'table', 'commons', 'util', 'totalFilter', 'util'], function () {
                form = layui.form, layer = layui.layer, laydate = layui.laydate, upload = layui.upload,
                    totalFilter = layui.totalFilter, util = layui.util,
                    setter = layui.setter, table = layui.table, commons = layui.commons;

                var tableId = '${tableId}';
                //$("#conditionIframe").attr("src", serverPath.formPath + setter.formLinkPath + "formDef/view/queryField?tableId=" + tableId);
                //$("#sortIframe").attr("src", serverPath.formPath + setter.formLinkPath + "formDef/view/sortField?tableId=" + tableId);
                $('#cancel').click(function () {
                    window.close();
                });

                $("#editTemplate").on('click', function () {
                    window.open(serverPath.formPath + setter.formLinkPath + 'formDef/view/editingTemplate?formKey=' + formKey);
                });
                //流程选择
                $("#opt").on('click', function () {
                    layer.open({
                        type: 2,
                        title: "流程选择",
                        shade: 0.3,
                        area: ['850px', '545px'],
                        content: serverPath.formPath + setter.formLinkPath + 'formDef/view/actDefModel'
                    })
                });

                //重置
                $("#reset").on('click', function () {
                    $('#subject').val("");
                    $('#defId').val("");
                });

                //权限下拉选项
                var rightOptionHtml = " <option value=''>请选择</option>" +
                    "                  <option value='none'>无</option>" +
                    "                  <option value='everyone'>所有人</option>" +
                    "                  <option value='user'>用户</option>" +
                    "                  <option value='role'>角色</option>" +
                    "                  <option value='org'>组织</option>" +
                    "                  <option value='orgMgr'>组织负责人</option>" +
                    "                  <option value='pos'>岗位</option>" +
                    "                  <option value='script'>脚本</option>";


                $(".btn-save").click(function () {
                    parent.layer.close(parent.layer.getFrameIndex(window.name));
                });
                form.on('radio(paging)', function (data) {
                    if (data.value == 1) {
                        $(".isPage").show();
                    } else {
                        $(".isPage").hide();
                    }
                });
                form.render();

//过滤条件页---开始
                $("#addFilter").on('click', function () {
                    layer.open({
                        type: 2,
                        title: "过滤窗口",
                        shade: 0.3,
                        area: ['900px', '510px'],
                        content: serverPath.formPath + setter.formLinkPath + 'formDef/view/filter?tableId=' + '${tableId}' + '&add=1'
                    })
                });

                var filterFields;

                //数据回显
                function filterFieldShow(filterField) {
                    if (filterField != null && filterField != "" && filterField != undefined) {
                        filterField = JSON.parse(filterField);
                        for (var i = 0; i < filterField.length; i++) {
                            filterField[i].id = i;
                            filterField[i].condition = JSON.stringify(filterField[i].condition);
                        }
                        filterFields = filterField;
                        loadFilterField(filterField);
                    } else {
                        filterField = [];
                        filterFields = filterField;
                        loadFilterField(filterField);
                    }
                }

                function getfilterField() {
                    var dataArray = [];
                    var arrayTr = $("#condition").next().find("tbody").children();
                    for (var i = 0; i < arrayTr.length; i++) {
                        var jsonTr = {};
                        var powerSelect = $($(arrayTr[i]).find("td").get(5)).find("select");
                        var powerValue = powerSelect.find("option:selected").val();//权限value
                        var condition = powerSelect.parents("td").prev().find("div").html();
                        var type = powerSelect.parents("td").prev().prev().find("div").html();
                        var key = powerSelect.parents("td").prev().prev().prev().find("div").html();
                        var name = powerSelect.parents("td").prev().prev().prev().prev().find("div").html();
                        var typeValue = "";
                        if ($.trim(type) == "SQL") {
                            typeValue = "2";
                        }
                        if ($.trim(type) == "条件脚本") {
                            typeValue = "1";
                        }
                        jsonTr.condition = condition;
                        jsonTr.type = typeValue;
                        jsonTr.key = key;
                        jsonTr.name = name;
                        jsonTr.right = [];
                        var jsonType = {};
                        jsonTr.right.push(jsonType);
                        jsonTr.right[0].type = powerValue;
                        if (powerValue == 'user' || powerValue == 'role' || powerValue == 'org' || powerValue == 'orgMgr' || powerValue == 'pos') {
                            jsonTr.right[0].ids = $(powerSelect.parent('div').next().find("input").get(1)).val();
                            jsonTr.right[0].names = $(powerSelect.parent('div').next().find("input").get(0)).val();
                        }
                        if (powerValue == 'script') {
                            jsonTr.right[0].script = $(powerSelect.parent('div').next().find("textarea").get(0)).val();
                            jsonTr.right[0].rightScript = $(powerSelect.parent('div').next().find("textarea").get(1)).val();
                        }
                        dataArray.push(jsonTr);
                    }
                    return dataArray;
                }


                //加载过滤条件 表
                function loadFilterField(condition) {
                    table.render({
                        elem: '#condition',
                        data: condition,
                        cols: [[
                            {type: 'checkbox', width: 30}
                            , {field: 'name', title: '名称', align: 'center', width: 120}
                            , {field: 'key', title: 'Key', align: 'center', width: 120}
                            , {field: 'type', title: '类型', align: 'center', width: 80, templet: '#filterTypeTemplate'}
                            , {field: 'condition', title: 'condition', align: 'center', hide: true}
                            , {
                                field: '',
                                title: '<div class="layui-form">权限<select class="layui-yonyou-select " lay-ignore="" onchange="selectFilterPower(this)" lay-filter="filterPower"> <option value="">请选择</option> <option value="none">无</option> <option value="everyone">所有人</option></select></div>',
                                templet: '#filterPowerTypeTemplate'
                            }
                            , {field: '', title: '管理', toolbar: "#filterRowOperation", align: 'center', width: 210}
                        ]],
                        done: function (res, curr, count) {
                            // 循环表格中每一行
                            $.each(res.data, function (i, item) {
                                //回显权限
                                var filterPowerName = item.id + 'FilterPowerType';
                                $("select[name='" + filterPowerName + "']").val(item.right[0].type);
                            });
                            form.render('select');
                        }
                    });
                }

                //监听权限select
                form.on('select(filterPowerType)', function (data) {
                    var element = $(data.elem);
                    var selectName = $(data.elem).find("option:selected").text();
                    var selectValue = $(data.elem).find("option:selected").val();//选择的select的值
                    var attrName = element.attr("name");
                    var tableIndex = attrName.substring(1, 0);
                    var ids = "idsFilterPower" + tableIndex;
                    var names = "namesFilterPower" + tableIndex;
                    var inputIndex = "FilterPower" + tableIndex;
                    element.parent('div').next().remove();//先删除下面的div
                    if (selectValue == 'user' || selectValue == 'role' || selectValue == 'org' || selectValue == 'orgMgr' || selectValue == 'pos') {
                        //上一步已经删除了div，这一步在元素后接一个空的div powerType
                        element.parent('div').after('<div style="position: absolute; top: 0px; left: 198px;">\n' +
                            '            <input type="text" id="' + names + '" class="layui-input" value="" style="float: left;height: 30px;margin-right:5px;"/>\n' +
                            '            <button type="button" onclick="selectButton(this)" class="layui-btn layui-btn-xs selectUser" inputIndex="' + inputIndex + '">选择</button>\n' +
                            '            <input type="hidden" id="' + ids + '" value=""/>\n' +
                            '          </div>');
                    }
                    if (selectValue == 'script') {
                        element.parent('div').after(' <div style="position: absolute; top: 0px; left: 198px;">\n' +
                            '            <textarea class="layui-input" id="' + names + '" style="float: left;height: 30px;width: 200px;margin-right:5px;"></textarea>\n' +
                            '            <button type="button" onclick="selectScript(this)" class="layui-btn layui-btn-xs" inputIndex="' + inputIndex + '">常用脚本</button>\n' +
                            '            <textarea class="layui-input" id="' + ids + '" style="display:none;"></textarea>\n' +
                            '        </div>');
                    }
                });

                //添加子页面的数据
                layui.AddFilterField = function (res) {
                    res.id = filterFields.length;
                    var trLength = $("#condition").next().find("tbody").children().length;
                    $("#condition").next().find("div .layui-none").remove();
                    $("#condition").next().find("tbody").append(
                        '<tr data-index="' + trLength + '" class="">\n' +
                        '<td data-field="0" style="width: 30px" class="layui-table-col-special">\n' +
                        '<div class="layui-table-cell  laytable-cell-checkbox" style="width: 30px">\n' +
                        '<input type="checkbox" name="layTableCheckbox" lay-skin="primary">\n' +
                        '<div class="layui-unselect layui-form-checkbox" lay-skin="primary">\n' +
                        '<i class="layui-icon layui-icon-ok"></i>\n' +
                        '</div>\n' +
                        '</div>\n' +
                        '</td>\n' +
                        '<td data-field="name" style="width: 120px" align="center" class="">\n' +
                        '<div class="layui-table-cell " style="width: 120px" >' + res.name + '</div>\n' +
                        '</td>\n' +
                        '<td data-field="key" style="width: 120px" align="center" class="">\n' +
                        '<div class="layui-table-cell" style="width: 120px">' + res.key + '</div>\n' +
                        '</td>\n' +
                        '<td data-field="type" style="width: 80px" align="center" data-content="1" class="">\n' +
                        '<div class="layui-table-cell" style="width: 80px">' + res.type + '</div>\n' +
                        '</td>\n' +
                        '<td data-field="condition"  align="center" class="layui-hide">\n' +
                        '<div class="layui-table-cell ">' + res.condition + '</div>\n' +
                        '</td>\n' +
                        '<td data-field="5"  data-content="" class="layui-table-col-special">\n' +
                        '<div class="layui-table-cell"> \n' +
                        '<div class="filterPowerType"> \n' +
                        '<select class="layui-yonyou-select" lay-filter="filterPowerType" name="' + res.id + 'FilterPowerType">\n' +
                        '<option value="">请选择</option>\n' +
                        '<option value="none" selected>无</option> \n' +
                        '<option value="everyone">所有人</option> \n' +
                        '<option value="user">用户</option> \n' +
                        '<option value="role">角色</option> \n' +
                        '<option value="org">组织</option> \n' +
                        '<option value="orgMgr">组织负责人</option> \n' +
                        '<option value="pos">岗位</option> \n' +
                        '<option value="script">脚本</option> \n' +
                        '</select>\n' +
                        '<div class="layui-unselect layui-form-select">\n' +
                        '<div class="layui-select-title">\n' +
                        '<input type="text" placeholder="请选择" value="无" readonly="" class="layui-input layui-unselect">\n' +
                        '<i class="layui-edge"></i>\n' +
                        '</div>\n' +
                        '<dl class="layui-anim layui-anim-upbit">\n' +
                        '<dd lay-value="" class="layui-select-tips">请选择</dd>\n' +
                        '<dd lay-value="none" class="layui-this">无</dd>\n' +
                        '<dd lay-value="everyone" class="">所有人</dd>\n' +
                        '<dd lay-value="user" class="">用户</dd>\n' +
                        '<dd lay-value="role" class="">角色</dd>\n' +
                        '<dd lay-value="org" class="">组织</dd>\n' +
                        '<dd lay-value="orgMgr" class="">组织负责人</dd>\n' +
                        '<dd lay-value="pos" class="">岗位</dd>\n' +
                        '<dd lay-value="script" class="">脚本</dd>\n' +
                        '</dl>\n' +
                        '</div> \n' +
                        '</div>   \n' +
                        '</div>\n' +
                        '</td>\n' +
                        '<td data-field="5" style="width: 210px" align="center" data-off="true" class="layui-table-col-special">\n' +
                        '<div class="layui-table-cell" style="width: 210px" > \n' +
                        '<a class="layui-btn layui-btn-xs" lay-event="moveup">上移</a> \n' +
                        '<a class="layui-btn layui-btn-xs" lay-event="movedown">下移</a> \n' +
                        '<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a> \n' +
                        '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a> \n' +
                        '</div>\n' +
                        '</td>\n' +
                        '</tr>');
                    filterFields.push(res);
                    form.render('select')
                };

                //根据子页面提交的数据  修改主页面
                layui.EditFilterField = function (selectAttrName, res) {
                    $("select[name='" + selectAttrName + "']").parents("td").prev().find("div").html(res.condition);
                    $("select[name='" + selectAttrName + "']").parents("td").prev().prev().find("div").html(res.type);
                    $("select[name='" + selectAttrName + "']").parents("td").prev().prev().prev().find("div").html(res.key);
                    $("select[name='" + selectAttrName + "']").parents("td").prev().prev().prev().prev().find("div").html(res.name);
                };

                //获取主页面的数据
                layui.getFilterField = function (selectAttrName) {
                    var powerSelect = $("select[name='" + selectAttrName + "']");
                    var condition = powerSelect.parents("td").prev().find("div").html();
                    var type = powerSelect.parents("td").prev().prev().find("div").html();
                    var key = powerSelect.parents("td").prev().prev().prev().find("div").html();
                    var name = powerSelect.parents("td").prev().prev().prev().prev().find("div").html();
                    var typeValue = "";
                    if ($.trim(type) == "SQL") {
                        typeValue = "2";
                    }
                    if ($.trim(type) == "条件脚本") {
                        typeValue = "1";
                    }
                    return {"key": key, "name": name, "type": typeValue, "condition": condition};
                };

                // 上移 下移 编辑 删除
                table.on('tool(condition)', function (obj) {
                    var data_tr = $(this);
                    switch (obj.event) {
                        case 'del':
                            layer.confirm('确定删除当前数据吗？', {
                                btn: ['确定', '取消'] //按钮
                            }, function (index) {
                                var delObj = obj.data;
                                obj.del();
                                layer.close(index);
                            });
                            break;
                        case 'moveup':
                            var tr = $(data_tr).parent().parent().parent();
                            $(tr).insertBefore($(tr).prev());
                            break;
                        case 'movedown':
                            var tr = $(data_tr).parent().parent().parent();
                            $(tr).insertAfter($(tr).next());
                            break;
                        case 'edit':
                            var selectAttrName = $($(data_tr).parent().parent().prev()).find("select").attr("name");
                            layer.open({
                                type: 2,
                                title: "过滤窗口",
                                shade: 0.3,
                                area: ['900px', '510px'],
                                content: serverPath.formPath + setter.formLinkPath + 'formDef/view/filter?tableId=' + '${tableId}' + '&add=0&selectAttrName=' + selectAttrName
                            });
                            break;
                    }
                });
//过滤条件页---结束

                //查询业务数据模板列表
                $.ajax({
                    type: 'post',
                    dataType: 'json',
                    url: serverPath.formPath + setter.formLinkPath + "formTemplate/list",
                    data: {'templateType': 'dataTemplate'},
                    success: function (result) {
                        $.each(result.data, function (index, objVal) {
                            $("#templateAlias").append("<option value=" + objVal.alias + ">" + objVal.templateName + "</option>");
                        });
                        form.render();
                    }
                });


                /**
                 * 数据回写
                 */
                var dataTemplateId = "";
                var displayField;
                var exportField;
                var t_date = {};
                t_date.tableId = tableId;
                t_date.formKey = '${formKey}';

                //显示的列字段
                $.ajax({
                    url: serverPath.formPath + setter.formLinkPath + "table/getByTableId?tableId=" + tableId,
                    dataType: 'json',
                    success: function (data) {
                        fieldArr = data.data.fields;
                        var tableInfo = data.data.table;
                        table.render({
                            elem: '#fieldTable',
                            data: fieldArr,
                            height: 'full-180',
                            limit: 100,
                            cols: [[
                                {type: 'numbers', title: '序号', width: 60, align: 'center'}
                                , {field: 'fieldName', title: '列名', align: 'center'}
                                , {field: 'fieldDesc', title: '注释', align: 'center'}
                                , {field: 'fieldType', hide: true}
                                , {field: 'ctlProperty', hide: true}
                                , {field: 'sn', hide: true}
                                , {
                                    field: '',
                                    title: '<div class="layui-form">显示权限<select class="layui-yonyou-select " lay-ignore="" name="rightControl" id="rightControl" lay-filter="rightControl"> <option value="">请选择</option> <option value="none">无</option> <option value="everyone">所有人</option></select></div>',
                                    width: 500,
                                    templet: function (d) {
                                        return "<div class='displayPermission'><select class='layui-yonyou-select rightSelect' lay-filter='rightSelect' name='rightSelect' id='0" + tableId + "" + d.fieldName + "'>" + rightOptionHtml + " </select></div> ";
                                    }
                                }
                                , {field: 'right', title: '管理', width: 170, toolbar: "#rowOperation", align: 'center'}
                            ]], done: function (data) {
                                $("#tableInfo").text(tableInfo.tableDesc + "(" + tableInfo.tableName + ")");
                                $("#rightControl").change(function () {
                                    var displayFieldSelVal = $(this).val();
                                    $(".fieldTable select").val(displayFieldSelVal);
                                    $(".selectorDiv").remove();
                                    form.render('select');
                                });

                                form.on('select(rightSelect)', function (data) {
                                    var fieldName = $(this).parents(".layui-table-cell").parent().prev().prev().prev().prev().prev().children().text();
                                    var tableId = tableInfo.tableId;
                                    var namesAttr = "names0" + tableId + fieldName;
                                    var idsAttr = "ids0" + tableId + fieldName;
                                    var selectorHtml = "<div style='position: absolute; top: 0px; left: 198px;' class='selectorDiv'>";
                                    var userButton = "<input type='text'class='layui-input' style='float: left;height: 30px;margin-right:5px;' id='" + namesAttr + "'> <input type='hidden' id='" + idsAttr + "'><button type='button' onclick='selectButton(this)' class='layui-btn layui-btn-xs selectUser' inputIndex='0" + tableId + "" + fieldName + "'>选择</button></div>";
                                    var appendHtml = selectorHtml + userButton;
                                    var scriptButton = "<textarea class='layui-input' style='float: left;height: 30px;width: 222px;margin-right:5px;' id='" + namesAttr + "'></textarea> <input type='hidden' id='" + idsAttr + "'><button type='button' onclick='selectorScript(this)' class='layui-btn layui-btn-xs selectUser' inputIndex='0" + tableId + "" + fieldName + "'>选择</button></div>";
                                    $("#0" + tableId + fieldName).next().next().remove();
                                    if (data.value == 'script') {
                                        appendHtml = selectorHtml + scriptButton;
                                    }
                                    if (data.value != 'none' && data.value != 'everyone' && data.value != '') {
                                        $("#0" + tableId + fieldName).parent().append(appendHtml);
                                    }
                                })
                                //数据回写
                                showData();
                            }
                        });
                        form.render();
                    }
                });


                /**
                 * 组装导出字段json数据
                 * @param data   字段数据
                 */
                function getExportFieldArr(data) {
                    var exportFieldArr = [];
                    for (var j = 0; j < data.length; j++) {
                        var exportJson = {"tableId": "", "tableName": "", "tableDesc": "", "isMain": 1, "fields": []};
                        exportJson.tableId = data[j].table.tableId;
                        exportJson.tableName = data[j].table.tableName;
                        exportJson.tableDesc = data[j].table.tableDesc;
                        exportJson.isMain = data[j].table.isMain;
                        var fieldArr = [];
                        var fields = data[j].fields;
                        for (var i = 0; i < fields.length; i++) {
                            var jsonObj = {
                                "tableId": "",
                                "tableName": "",
                                "isMain": 1,
                                "name": "",
                                "desc": "",
                                "type": "",
                                "style": "",
                                "right": "",
                                "$$hashKey": ""
                            };
                            jsonObj.tableName = data[j].table.tableName;
                            jsonObj.tableId = data[j].table.tableId;
                            jsonObj.isMain = data[j].table.isMain;
                            jsonObj.name = fields[i].fieldName;
                            jsonObj.desc = fields[i].fieldDesc;
                            jsonObj.type = fields[i].fieldType;
                            jsonObj.style = 'yyyy-MM-dd';
                            if (fields[i].ctlProperty != '' && fields[i].fieldType == 'date') {
                                jsonObj.style = JSON.parse(fields[i].ctlProperty).format;
                            }
                            //字段权限
                            var fieldRightArray = [];
                            var inputIndex = "1" + exportJson.tableId + fields[i].fieldName;
                            var selVal = $("#" + inputIndex).val();
                            fieldRightArray.push(getFieldRights(selVal, inputIndex));
                            jsonObj.right = fieldRightArray;
                            fieldArr.push(jsonObj);
                        }
                        exportJson.fields = fieldArr;
                        exportFieldArr.push(exportJson);
                    }
                    return exportFieldArr;
                }

                /**
                 * 组装显示列字段json数据
                 * @param data   字段数据
                 */
                function getDisplayFieldArr(data) {
                    var displayFieldArr = [];
                    var fields = data;
                    var json = {
                        "s": 1,
                        "type": "none",
                        "id": "",
                        "name": "",
                        "script": ""
                    };
                    for (var i = 0; i < fields.length; i++) {
                        var jsonObj = {"name": "", "desc": "", "type": "", "style": "", "right": ""};
                        jsonObj.name = fields[i].fieldName;
                        jsonObj.desc = fields[i].fieldDesc;
                        jsonObj.type = fields[i].fieldType;
                        jsonObj.style = 'yyyy-MM-dd';
                        if (fields[i].ctlProperty != '' && fields[i].fieldType == 'date') {
                            jsonObj.style = JSON.parse(fields[i].ctlProperty).format;
                        }
                        var mainTableId = '${tableId}';
                        //字段权限
                        var fieldRightArray = [];
                        var inputIndex = "0" + mainTableId + fields[i].fieldName;
                        var selVal = $("#" + inputIndex).val();
                        fieldRightArray.push(getFieldRights(selVal, inputIndex));
                        fieldRightArray.push(json);
                        jsonObj.right = fieldRightArray;
                        displayFieldArr.push(jsonObj);
                    }
                    return displayFieldArr;
                }

                //通过选中的权限范围 组装权限json对象
                function getFieldRights(selVal, inputIndex) {
                    var jsonObj = {};
                    jsonObj.type = selVal;
                    var names = $("#names" + inputIndex).val();
                    var ids = $("#ids" + inputIndex).val();
                    //加上各种选择器的
                    if (selVal != 'none' && selVal != 'everyone' && selVal != '' && selVal != 'script') {
                        jsonObj.names = names;
                        jsonObj.ids = ids;
                    }
                    if (selVal == 'script') {
                        jsonObj.rightScript = names;
                        jsonObj.script = names;
                    }
                    return jsonObj;
                }

                /**
                 * 数据回写
                 */
                function showData() {
                    $.ajax({
                        url: serverPath.formPath + setter.formLinkPath + "dataTemplate/get",
                        type: "get",
                        contentType: 'application/json',
                        dataType: 'json',
                        data: t_date,
                        success: function (data) {
                            var returnDate = data.data;
                            var manageFields;
                            var filterFields;
                            if (null != returnDate) {
                                dataTemplateId = returnDate.id;
                                displayField = returnDate.displayField;
                                exportField = returnDate.exportField;
                                manageFields = returnDate.manageField;
                                filterFields = returnDate.filterField;
                                sortField = returnDate.sortField;
                                conditionField = returnDate.conditionField;
                                form.val('templateForm', {
                                    "needPage": returnDate.needPage + "",
                                    "pageSize": returnDate.pageSize,
                                    "isQuery": returnDate.isQuery + "",
                                    "isFilter": returnDate.isFilter + "",
                                    "templateAlias": returnDate.templateAlias,
                                    "defId": returnDate.defId,
                                    "subject": returnDate.subject
                                });
                                if (returnDate.needPage == 1) {
                                    $(".isPage").show();
                                } else {
                                    $(".isPage").hide();
                                }
                                fieldRightShow("0", displayField);
                                fieldRightShow("1", exportField);
                                form.render('select');
                            }
                            manageFieldShow(manageFields);
                            filterFieldShow(filterFields);
                            $("#conditionIframe").attr("src", serverPath.formPath + setter.formLinkPath + "formDef/view/queryField?tableId=" + tableId);
                            $("#sortIframe").attr("src", serverPath.formPath + setter.formLinkPath + "formDef/view/sortField?tableId=" + tableId);
                        }
                    });
                }

                /**
                 * 回显显示列字段和导出字段的权限信息
                 * @param type  0显示列字段  1导出字段
                 * @param fieldStr 要回写的数据
                 */
                function fieldRightShow(type, fieldStr) {
                    var fieldStrObj = JSON.parse(fieldStr);
                    if (type == "1") {
                        for (var j = 0; j < fieldStrObj.length; j++) {
                            showRightInfo(type, fieldStrObj[j].fields);
                        }
                    }
                    else if (type == "0") {
                        showRightInfo(type, fieldStrObj);
                    }
                }

                /**
                 * 回写查询列字段和导出字段的数据
                 * @param type
                 * @param fieldStrObj
                 */
                function showRightInfo(type, fieldStrObj) {
                    for (var i = 0; i < fieldStrObj.length; i++) {
                        var fieldName = fieldStrObj[i].name;
                        var right = fieldStrObj[i].right;
                        var rightValue = right[0].type;
                        if (type == "1") {
                            tableId = fieldStrObj[i].tableId;
                        } else {
                            tableId = '${tableId}';
                        }
                        $("#" + type + tableId + fieldName).val(right[0].type);
                        //选择器类型的赋值
                        if (rightValue != 'none' && rightValue != 'everyone' && rightValue != '') {
                            var namesAttr = "names" + type + tableId + fieldName;
                            var idsAttr = "ids" + type + tableId + fieldName;
                            var selectorHtml = "<div style='position: absolute; top: 0px; left: 198px;' class='selectorDiv'>";
                            var inputIndex = type + tableId + fieldName;
                            var userButton = "<input type='text'class='layui-input' style='float: left;height: 30px;margin-right:5px;' id='" + namesAttr + "'> <input type='hidden' id='" + idsAttr + "'><button type='button' onclick='selectButton(this)' class='layui-btn layui-btn-xs selectUser' inputIndex='" + inputIndex + "'>选择</button></div>";
                            var scriptButton = "<textarea class='layui-input' style='float: left;height: 30px;width: 222px;margin-right:5px;' id='" + namesAttr + "'></textarea> <input type='hidden' id='" + idsAttr + "'><button type='button' onclick='selectorScript(this)' class='layui-btn layui-btn-xs selectUser' inputIndex='" + inputIndex + "'>选择</button></div>";
                            var appendHtml = selectorHtml + userButton;
                            $("#" + type + tableId + fieldName).next().next().remove();
                            if (rightValue == 'script') {
                                appendHtml = selectorHtml + scriptButton;
                            }
                            if (rightValue != 'none' && rightValue != 'everyone' && rightValue != '') {
                                $("#" + type + tableId + fieldName).parent().append(appendHtml);
                            }
                            if (rightValue == 'script') {
                                $("#" + namesAttr).val(right[0].rightScript);
                                $("#" + idsAttr).val(right[0].script);
                            } else {
                                $("#" + namesAttr).val(right[0].names);
                                $("#" + idsAttr).val(right[0].ids);
                            }
                        }
                    }
                }

                /**
                 * 保存
                 */
                form.on('submit(dataTemplateForm)', function (data) {
                    var displayFieldData = [];
                    $('.fieldTable .layui-table-body tr').each(function (i, item) {
                        var jsonObj = {
                            "fieldName": "",
                            "fieldDesc": "",
                            "fieldType": "",
                            "ctlProperty": ""
                        };
                        var tdInfo = $(item).children();
                        jsonObj.fieldName = $.trim(tdInfo[1].textContent);
                        jsonObj.fieldDesc = $.trim(tdInfo[2].textContent);
                        jsonObj.fieldType = $.trim(tdInfo[3].textContent);
                        jsonObj.ctlProperty = $.trim(tdInfo[4].textContent);
                        displayFieldData.push(jsonObj);
                    });

                    //排序字段
                    var sortFieldData = [];
                    var sortFieldDiv = $("#sortIframe").contents().find("#sortField div[lay-id='right-table-1'] .layui-table-body tr");
                    sortFieldDiv.each(function (i, item) {
                        var jsonObj = {
                            "name": "",
                            "desc": "",
                            "fieldType": "",
                            "sort": ""
                        };
                        var tdInfo = $(item).children();
                        jsonObj.name = $.trim(tdInfo[1].textContent);
                        jsonObj.desc = $.trim(tdInfo[2].textContent);
                        jsonObj.fieldType = $.trim(tdInfo[3].textContent);
                        jsonObj.sort = $(item).find('select').val();
                        sortFieldData.push(jsonObj);
                    });
                    var displayField = JSON.stringify(getDisplayFieldArr(displayFieldData));
                    var exportField = JSON.stringify(getExportFieldArr(exportFieldData));
                    var sortField = JSON.stringify(sortFieldData);

                    //获取manageField全部数据-----开始
                    var dataArray = [];
                    var arrayTr = $("#functionField").next().find("tbody").children();
                    for (var i = 0; i < arrayTr.length; i++) {
                        var jsonTr = {};
                        var powerSelect = $($(arrayTr[i]).find("td").get(3)).find("select");
                        var powerValue = powerSelect.find("option:selected").val();//权限value
                        var typeValue = powerSelect.parents("td").prev().find("select").find("option:selected").val();//类型value
                        var typeName = powerSelect.parents("td").prev().find("select").find("option:selected").text();//类型text
                        jsonTr.desc = typeName;
                        jsonTr.name = typeValue;
                        jsonTr.right = [];
                        var jsonType = {};
                        jsonTr.right.push(jsonType);
                        jsonTr.right[0].type = powerValue;
                        if (powerValue == 'user' || powerValue == 'role' || powerValue == 'org' || powerValue == 'orgMgr' || powerValue == 'pos') {
                            jsonTr.right[0].ids = $(powerSelect.parent('div').next().find("input").get(1)).val();
                            jsonTr.right[0].names = $(powerSelect.parent('div').next().find("input").get(0)).val();
                        }
                        if (powerValue == 'script') {
                            jsonTr.right[0].script = $(powerSelect.parent('div').next().find("textarea").get(0)).val();
                            jsonTr.right[0].rightScript = $(powerSelect.parent('div').next().find("textarea").get(1)).val();
                        }
                        for (var j = 0; j < dataArray.length; j++) {
                            if (typeValue == dataArray[j].name) {
                                layer.alert("功能按钮出现重复的类型，请检查!");
                                return false;
                            }
                        }
                        dataArray.push(jsonTr);
                    }
                    //获取条件字段的json设置数据
                    var conditionField = getConditionFiledArr();
                    //获取manageField全部数据-----结束
                    var jsonData = {
                        "conditionField": "[]",
                        "sortField": "[]",
                        "filterField": getfilterField(),
                        "manageField": dataArray,
                        "exportField": "[]",
                        "displayField": "[]"
                    };
                    jsonData.displayField = displayField;
                    jsonData.exportField = exportField;
                    jsonData.sortField = sortField;
                    jsonData.conditionField = conditionField;
                    jsonData.tableId = '${tableId}';
                    jsonData.formKey = data.field.formKey;
                    jsonData.isFilter = data.field.isFilter;
                    jsonData.isQuery = data.field.isQuery;
                    jsonData.needPage = data.field.needPage;
                    jsonData.pageSize = data.field.pageSize;
                    jsonData.templateAlias = data.field.templateAlias;
                    jsonData.subject = data.field.subject;
                    jsonData.id = dataTemplateId;
                    jsonData.defId = $('#defId').val();
                    if (dataTemplateCount > 0) {
                        layer.confirm('保存会覆盖模板，如果修改了模板请手动保存模板后再进行保存业务数据模板，是否继续保存？', function () {
                            saveDataTemplateAjax(jsonData);
                        })
                    } else {
                        saveDataTemplateAjax(jsonData);
                    }
                });

                /**
                 * 保存业务数据模板
                 */
                function saveDataTemplateAjax(jsonData) {
                    $.ajax({
                        url: serverPath.formPath + setter.formLinkPath + "dataTemplate/add",
                        dataType: 'json',
                        type: "post",
                        data: {"json": JSON.stringify(jsonData)},
                        success: function (result) {
                            if (commons._filterRecord(result)) {
                                layer.alert(result.msg, {skin: 'btn-class'}, function () {
                                    var index = parent.layer.getFrameIndex(window.name);

                                    parent.layui.table.reload('customForm', {
                                        page: {
                                            curr: 1
                                        }
                                    });
                                    parent.layui.totalFilter.init('customForm');
                                    commons._bulletWindow(index);
                                });
                            } else {
                                window.parent.layer.alert(result.msg);
                            }
                        }
                    });
                }

                /**
                 * 获取条件字段的json设置数据
                 */
                function getConditionFiledArr() {
                    //查询条件字段
                    var conditionFieldData = [];
                    var conditionFieldDiv = $("#conditionIframe").contents().find("#querysField div[lay-id='right-table-1'] .layui-table-body.layui-table-main tr");
                    conditionFieldDiv.each(function (i, item) {
                        var jsonObj = {};
                        var tdInfo = $(item).children();
                        jsonObj.na = $.trim(tdInfo[1].textContent); //名称
                        jsonObj.cm = $.trim(tdInfo[2].textContent); //注释
                        jsonObj.ty = $.trim(tdInfo[3].textContent); //字段类型

                        var selects = $(item).find('select');
                        jsonObj.ct = selects.eq(0).val(); //控件类型
                        jsonObj.op = selects.eq(1).val();
                        //条件
                        jsonObj.vf = selects.eq(2).val();
                        //值来源
                        jsonObj.va = "";
                        jsonObj.qt = getConditionQtByType(jsonObj);
                        conditionFieldData.push(jsonObj);
                    });
                    return JSON.stringify(conditionFieldData);
                }

                /**
                 * 根据条件字段的类型和选择的条件返回不同的qt值
                 * @param cd
                 * @returns {string|*}
                 */
                function getConditionQtByType(cd) {
                    var type = cd.ty;
                    var op = cd.op;
                    switch (type) {
                        case 'varchar' :
                            if (op) {
                                switch (op) {
                                    case "1" :
                                    case "2" :
                                        cd.qt = 'S';
                                        break;
                                    case "3" :
                                        cd.qt = 'SL';
                                        break;
                                    case "4" :
                                        cd.qt = 'SLL';
                                        break;
                                    case "5" :
                                        cd.qt = 'SLR';
                                        break;
                                    default :
                                        cd.qt = 'S';
                                        break;
                                }
                            }
                            break;
                        case 'number' :
                            cd.qt = 'L';
                            break;
                        case 'int' :
                            cd.qt = 'N';
                            break;
                        case 'date' :
                            if (op === "6")
                                cd.qt = 'DR';
                            else
                                cd.qt = 'DL';
                            break;
                        default :
                            cd.qt = 'S';
                            break;
                    }
                    return cd.qt;
                }


                var newSetterArray = [];
                table.on('tool(fieldTable)', function (obj) {
                    newSetterArray = [];
                    data_tr = $(this);
                    switch (obj.event) {
                        case 'del':
                            layer.confirm('确定删除当前数据吗？', {
                                btn: ['确定', '取消'] //按钮
                            }, function (index) {
                                var delObj = obj.data;
                                obj.del();
                                layer.close(index);
                            });
                            break;
                        case 'moveup':
                            var tr = $(data_tr).parent().parent().parent();
                            $(tr).insertBefore($(tr).prev());
                            break;
                        case 'movedown':
                            var tr = $(data_tr).parent().parent().parent();
                            $(tr).insertAfter($(tr).next());
                            break;
                    }
                });
                var exportFieldData = [];
                $.ajax({
                    url: serverPath.formPath + setter.formLinkPath + 'table/getTableDetail?tableId=' + tableId,
                    dataType: 'json',
                    async: false,
                    success: function (data) {
                        var returnData = data.data.fields;
                        isOutTable = data.data.table.isExternal;
                        exportFieldData.push(data.data);
                        var subList = data.data.subList;
                        //表格渲染数据
                        table.render({
                            elem: '#exportField',
                            data: returnData,
                            limit: 100,
                            cols: [[
                                {type: 'numbers', title: '序号', align: 'center'}
                                , {field: 'fieldName', title: '列名', align: 'center', width: 220}
                                , {field: 'fieldDesc', title: '注释', align: 'center', width: 220}
                                , {
                                    field: 'fieldType',
                                    title: '导出权限<select class="layui-yonyou-select" lay-ignore="" id="exportRight" name="power"> <option value="">请选择</option> <option value="none">无</option> <option value="everyone">所有人</option></select>',
                                    templet: function (d) {
                                        return "<div class='displayPermission'><select class='layui-yonyou-select rightSelect' lay-filter='exportRightMain' name='rightSelect' id='1" + tableId + "" + d.fieldName + "'>" + rightOptionHtml + " </select></div> ";
                                    }
                                }
                            ]], done: function (data) {
                                $("#exportRight").change(function () {
                                    var exportFieldSelVal = $(this).val();
                                    $(".exportField select").val(exportFieldSelVal);
                                    $(".selectorDiv").remove();
                                    form.render('select');
                                });
                                form.on('select(exportRightMain)', function (data) {
                                    var fieldName = $(this).parents(".layui-table-cell").parent().prev().prev().children().text();
                                    exportRightProcess(returnData[0].tableId, fieldName, data);
                                })
                            }
                        });

                        for (var i = 0; i < subList.length; i++) {
                            var idStr = 'childTable' + i;
                            var html = "<p style='margin:0 auto;text-align: center;padding:15px 0'>" + subList[i].tableDesc + "(" + subList[i].tableName + ")</p><table id='" + idStr + "'></table>";
                            $(".childTable").append(html);
                        }

                        for (var i = 0; i < subList.length; i++) {
                            var subTableId = subList[i].tableId;
                            var idStr = 'childTable' + i;
                            $.ajax({
                                url: serverPath.formPath + setter.formLinkPath + 'table/getByTableId?tableId=' + subTableId,
                                dataType: 'json',
                                async: false,
                                success: function (data) {
                                    exportFieldData.push(data.data);
                                    //表格渲染数据
                                    table.render({
                                        elem: $("#" + idStr),
                                        data: data.data.fields,
                                        limit: 100,
                                        // height:'full-500',
                                        cols: [[
                                            {type: 'numbers', align: 'center'}
                                            , {field: 'fieldName', align: 'center', width: 220}
                                            , {field: 'fieldDesc', align: 'center', width: 220}
                                            , {
                                                field: 'fieldType',
                                                templet: function (d) {
                                                    return "<div class='displayPermission' id='"+subTableId+"'><select class='layui-yonyou-select rightSelect' lay-filter='exportRightSub' name='rightSelect' id='1" + subTableId + "" + d.fieldName + "'>" + rightOptionHtml + " </select></div> ";
                                                }
                                            }
                                        ]], done: function (data) {
                                            form.on('select(exportRightSub)', function (data) {
                                                var fieldName = $(this).parents(".layui-table-cell").parent().prev().prev().children().text();
                                                var subTabId = $(this).parents(".displayPermission").attr("id");
                                                exportRightProcess(subTabId, fieldName, data);
                                            })
                                        }
                                    });
                                }
                            });
                        }
                    }
                });

                function exportRightProcess(newTableId, fieldName, data) {
                    var namesAttr = "names1" + newTableId + fieldName;
                    var idsAttr = "ids1" + newTableId + fieldName;
                    var selectorHtml = "<div style='position: absolute; top: 0px; left: 198px;' class='selectorDiv'>";
                    var userButton = "<input type='text'class='layui-input' style='float: left;height: 30px;margin-right:5px;' id='" + namesAttr + "'> <input type='hidden' id='" + idsAttr + "'><button type='button' onclick='selectButton(this)' class='layui-btn layui-btn-xs selectUser' inputIndex='1" + newTableId + "" + fieldName + "'>选择</button></div>";
                    var scriptButton = "<textarea class='layui-input' style='float: left;height: 30px;width: 222px;margin-right:5px;' id='" + namesAttr + "'></textarea> <input type='hidden' id='" + idsAttr + "'><button type='button' onclick='selectorScript(this)' class='layui-btn layui-btn-xs selectUser' inputIndex='1" + newTableId + "" + fieldName + "'>选择</button></div>";
                    var appendHtml = selectorHtml + userButton;
                    $("#1" + newTableId + fieldName).next().next().remove();
                    if (data.value == 'script') {
                        appendHtml = selectorHtml + scriptButton;
                    }
                    if (data.value != 'none' && data.value != 'everyone' && data.value != '') {
                        $("#1" + newTableId + fieldName).parent().append(appendHtml);
                    }
                }

//功能按钮页---开始
                //数据回显
                var manageField;

                function manageFieldShow(manageFields) {
                    if (manageFields != null && manageFields != "" && manageFields != undefined) {
                        manageField = JSON.parse(manageFields);
                        if (manageField.length > 0) {
                            for (var j = 0; j < manageField.length; j++) {
                                manageField[j].id = j;
                            }
                            loadFunctionField(manageField);
                        } else {
                            var empty = [];
                            loadFunctionField(empty);
                        }
                    } else {
                        var empty = [];
                        loadFunctionField(empty);
                    }
                }

                //初始化数据
                var initData = JSON.parse('[{"desc":"新增","name":"add","right":[{"type":"none"}]},{"desc":"编辑","name":"edit","right":[{"type":"none"}]},{"desc":"批量删除","name":"batchDel","right":[{"type":"none"}]},{"desc":"删除","name":"del","right":[{"type":"none"}]},{"desc":"明细","name":"detail","right":[{"type":"none"}]},{"desc":"导出","name":"export","right":[{"type":"none"}]},{"desc":"导入","name":"import","right":[{"type":"none"}]},{"desc":"启动流程","name":"start","right":[{"type":"none"}]},{"desc":"重启流程","name":"reStart","right":[{"type":"none"}]}]');

                //  添加按钮
                $("#btnFunctionAdd").on('click', function () {
                    var count;
                    if (manageField == undefined) {
                        count = 0;
                    } else {
                        count = manageField.length;
                    }
                    var functionType = count + "FunctionType";
                    var powerType = count + "PowerType";
                    $("#functionField").next().find("div .layui-none").remove();//去掉 无数据三个字
                    $("#functionField").next().find("tbody").append(
                        '<tr data-index="' + count + '" class="buttonFiled">\n' +
                        '<td data-field="0" data-key="4-0-0" style="width: 40px" align="center" class="layui-table-col-special">\n' +
                        '<div class="layui-table-cell laytable-cell-4-0-0 laytable-cell-checkbox">\n' +
                        '<input type="checkbox" name="layTableCheckbox" lay-skin="primary">\n' +
                        '<div class="layui-unselect layui-form-checkbox" lay-skin="primary">\n' +
                        '<i class="layui-icon layui-icon-ok"></i>\n' +
                        '</div>\n' +
                        '</div>\n' +
                        '</td>\n' +
                        '<td data-field="desc" data-key="4-0-1" style="width: 170px" align="center" data-content="新增" class="">\n' +
                        '<div class="layui-table-cell laytable-cell-4-0-1" style="width: 170px">\n' +
                        '<input type="text" class="layui-input" value="新增" style="display:inline-block;width:100%">\n' +
                        '</div>\n' +
                        '</td>\n' +
                        '<td data-field="desc" data-key="4-0-2"  style="width: 170px" align="center" data-content="新增" class="">\n' +
                        '<div class="layui-table-cell laytable-cell-4-0-2" style="width: 170px"> \n' +
                        '<div id="functionType"> \n' +
                        '<select class="layui-yonyou-select" lay-filter="functionType" name="' + functionType + '"> \n' +
                        '<option value="add">新增</option> \n' +
                        '<option value="edit">编辑</option> \n' +
                        '<option value="batchDel">批量删除</option> \n' +
                        '<option value="del">删除</option> \n' +
                        '<option value="detail">明细</option> \n' +
                        '<option value="export">导出</option> \n' +
                        '<option value="import">导入</option> \n' +
                        '<option value="start">启动流程</option> \n' +
                        '<option value="reStart">重启流程</option> \n' +
                        '</select><div class="layui-unselect layui-form-select">\n' +
                        '<div class="layui-select-title">\n' +
                        '<input type="text" placeholder="请选择" value="新增" readonly="" class="layui-input layui-unselect">\n' +
                        '<i class="layui-edge"></i>\n' +
                        '</div>\n' +
                        '<dl class="layui-anim layui-anim-upbit" style="">\n' +
                        '<dd lay-value="add" class="layui-this">新增</dd>\n' +
                        '<dd lay-value="edit" class="">编辑</dd>\n' +
                        '<dd lay-value="batchDel" class="">批量删除</dd>\n' +
                        '<dd lay-value="del" class="">删除</dd>\n' +
                        '<dd lay-value="detail" class="">明细</dd>\n' +
                        '<dd lay-value="export" class="">导出</dd>\n' +
                        '<dd lay-value="import" class="">导入</dd>\n' +
                        '<dd lay-value="start" class="">启动流程</dd>\n' +
                        '<dd lay-value="reStart" class="">重启流程</dd>\n' +
                        '</dl>\n' +
                        '</div> \n' +
                        '</div> \n' +
                        '</div>\n' +
                        '</td>\n' +
                        '<td data-field="3" data-key="4-0-3" data-content="" class="layui-table-col-special">\n' +
                        '<div class="layui-table-cell laytable-cell-4-0-3"> \n' +
                        '<div class="powerType"> \n' +
                        '<select class="layui-yonyou-select" lay-filter="powerType" name="' + powerType + '"> \n' +
                        '<option value="">请选择</option> \n' +
                        '<option value="none" selected>无</option> \n' +
                        '<option value="everyone">所有人</option> \n' +
                        '<option value="user">用户</option> \n' +
                        '<option value="role">角色</option> \n' +
                        '<option value="org">组织</option> \n' +
                        '<option value="orgMgr">组织负责人</option> \n' +
                        '<option value="pos">岗位</option> \n' +
                        '<option value="script">脚本</option> \n' +
                        '</select>\n' +
                        '<div class="layui-unselect layui-form-select">\n' +
                        '<div class="layui-select-title">\n' +
                        '<input type="text" placeholder="请选择" value="所有人" readonly="" class="layui-input layui-unselect">\n' +
                        '<i class="layui-edge"></i>\n' +
                        '</div>\n' +
                        '<dl class="layui-anim layui-anim-upbit" style="">\n' +
                        '<dd lay-value="" class="layui-select-tips">请选择</dd>\n' +
                        '<dd lay-value="none" class="layui-this">无</dd>\n' +
                        '<dd lay-value="everyone" class="">所有人</dd>\n' +
                        '<dd lay-value="user" class="">用户</dd>\n' +
                        '<dd lay-value="role" class="">角色</dd>\n' +
                        '<dd lay-value="org" class="">组织</dd>\n' +
                        '<dd lay-value="orgMgr" class="">组织负责人</dd>\n' +
                        '<dd lay-value="pos" class="">岗位</dd>\n' +
                        '<dd lay-value="script" class="">脚本</dd>\n' +
                        '</dl>\n' +
                        '</div>\n' +
                        '</div>   \n' +
                        '</div>\n' +
                        '</td>\n' +
                        '<td data-field="right" data-key="4-0-4" style="width: 170px" align="center" data-off="true" class="">\n' +
                        '<div class="layui-table-cell laytable-cell-4-0-4" style="width: 170px"> \n' +
                        '<a class="layui-btn layui-btn-xs" lay-event="moveup">上移</a> \n' +
                        '<a class="layui-btn layui-btn-xs" lay-event="movedown">下移</a> \n' +
                        '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a> \n' +
                        '</div>\n' +
                        '</td>\n' +
                        '</tr>');
                    form.render();
                    manageField.push({
                        "desc": '新增',
                        "name": "add",
                        "right": [{"type": "none"}],
                        "id": manageField.length
                    });
                });

                // 初始化按钮
                $("#btnFunctionInit").on('click', function () {
                    for (var j = 0; j < initData.length; j++) {
                        initData[j].id = j;
                    }
                    loadFunctionField(initData);
                    manageField = initData;
                });

                function loadFunctionField(res) {
                    table.render({
                        elem: '#functionField',
                        data: res,
                        cols: [[
                            {type: 'checkbox', title: '选择', width: 40, align: 'center'}
                            , {
                                field: 'desc', title: '名称', align: 'center', width: 170,
                                templet: function (d) {
                                    return '<input type="text" class="layui-input" value="' + d.desc + '" style="display:inline-block">';
                                }
                            }
                            , {
                                field: 'desc',
                                title: '类型',
                                align: 'center',
                                width: 170,
                                templet: '#functionTypeTemplate'
                            }
                            , {
                                field: '',
                                title: '<div class="layui-form">权限<select class="layui-yonyou-select " lay-ignore="" onchange="selectPower(this)" lay-filter="functionPower"> <option value="">请选择</option> <option value="none">无</option> <option value="everyone">所有人</option></select></div>',
                                templet: '#powerTypeTemplate'
                            }
                            , {field: 'right', title: '管理', width: 170, toolbar: "#rowOperation", align: 'center'}
                        ]], done: function (res, curr, count) {
                            // 循环表格中每一行
                            $.each(res.data, function (i, item) {
                                //回显类型
                                var typeName = item.id + 'FunctionType';
                                $("select[name='" + typeName + "']").val(item.name);
                                //回显权限
                                var powerName = item.id + 'PowerType';
                                $("select[name='" + powerName + "']").val(item.right[0].type);
                            });
                            form.render('select');
                        }
                    });
                }

                //监听类型select
                form.on('select(functionType)', function (data) {
                    var typeName = $(data.elem).find("option:selected").text();
                    var typeValue = $(data.elem).find("option:selected").val();
                    $(data.elem).parents("td").prev().find("input").val(typeName);
                });

                //监听权限select
                form.on('select(powerType)', function (data) {
                    var element = $(data.elem);
                    var selectName = $(data.elem).find("option:selected").text();
                    var selectValue = $(data.elem).find("option:selected").val();//选择的select的值
                    var attrName = element.attr("name");
                    var tableIndex = attrName.substring(1, 0);
                    var ids = "idsPower" + tableIndex;
                    var names = "namesPower" + tableIndex;
                    var inputIndex = "Power" + tableIndex;
                    element.parent('div').next().remove();//先删除下面的div
                    if (selectValue == 'user' || selectValue == 'role' || selectValue == 'org' || selectValue == 'orgMgr' || selectValue == 'pos') {
                        //上一步已经删除了div，这一步在元素后接一个空的div powerType
                        element.parent('div').after('<div style="position: absolute; top: 0px; left: 198px;">\n' +
                            '            <input type="text" id="' + names + '" class="layui-input" value="" style="float: left;height: 30px;margin-right:5px;width:180px"/>\n' +
                            '            <button type="button" onclick="selectButton(this)" class="layui-btn layui-btn-xs selectUser" inputIndex="' + inputIndex + '">选择</button>\n' +
                            '            <input type="hidden" id="' + ids + '" value=""/>\n' +
                            '          </div>');
                    }
                    if (selectValue == 'script') {
                        element.parent('div').after(' <div style="position: absolute; top: 0px; left: 198px;">\n' +
                            '            <textarea class="layui-input" id="' + names + '" style="float: left;height: 30px;width: 200px;margin-right:5px;"></textarea>\n' +
                            '            <button type="button" onclick="selectScript(this)" class="layui-btn layui-btn-xs" inputIndex="' + inputIndex + '">常用脚本</button>\n' +
                            '            <textarea class="layui-input" id="' + ids + '" style="display:none;"></textarea>\n' +
                            '        </div>');
                    }
                });
                // 上移 下移  删除
                table.on('tool(functionField)', function (obj) {
                    var data_tr = $(this);
                    switch (obj.event) {
                        case 'del':
                            layer.confirm('确定删除当前数据吗？', {
                                btn: ['确定', '取消'] //按钮
                            }, function (index) {
                                var delObj = obj.data;
                                obj.del();
                                layer.close(index);
                            });
                            break;
                        case 'moveup':
                            var tr = $(data_tr).parent().parent().parent();
                            $(tr).insertBefore($(tr).prev());
                            break;
                        case 'movedown':
                            var tr = $(data_tr).parent().parent().parent();
                            $(tr).insertAfter($(tr).next());
                            break;
                    }
                });
//功能按钮页---结束
            })


        </script>
        <style scoped>
            .layui-input, .layui-textarea {
                height: 30px !important;
            }

            #filterCell .layui-table-body {
                height: 400px;
                overflow-y: auto;
            }

            .layui-table-box {
                overflow: visible;
            }

            #buttonBox .layui-table-body {
                height: 400px;
                overflow-y: auto;
                overflow-x: hidden;
            }

            .childTable .layui-table-header {
                height: 0;
            }
            .layui-table-box,.layui-table-body{
                position: relative;
                overflow: inherit!important;
            }
            .layui-form-select dl{
                height: 250px;
            }
        </style>
    </body>
</html>